import { likePost } from '@/api/home'
import { patientConsultPrescription } from '@/api/room'
import { patientOrder, patientOrderCancel } from '@/api/user'
import { OrderType } from '@/enums'
import type { homePageDocApiRowsItem } from '@/types/home'
import type { likePostReqType, likeType, patientConsultOrderListApiRowsItem } from '@/types/user'
import { showImagePreview } from 'vant'
import { computed } from 'vue'
import { ref } from 'vue'
import { onBeforeUnmount } from 'vue'
// 屏幕宽度响应式处理
export const useWindowWidth = () => {
  const width = ref(window.innerWidth)
  const onResize = () => {
    width.value = window.innerWidth
  }
  window.addEventListener('resize', onResize)
  onBeforeUnmount(() => {
    window.removeEventListener('resize', onResize)
  })
  return { width }
}

// 关注
export const useLike = (type: likePostReqType = 'doc') => {
  const loading = ref(false)
  // 方法的参数，ts类型规则：实参的属性可以多于形参的属性，但是不能少
  const likeEvent = async (item: likeType) => {
    loading.value = true
    try {
      await likePost({
        type: type,
        id: item.id
      })
      // 1==> 0   0==>1
      item.likeFlag = item.likeFlag === 1 ? 0 : 1
      // item.likeFlag = (1 - item.likeFlag) as 0 | 1
    } finally {
      loading.value = false
    }
  }
  return { loading, likeEvent }
}

// 取消
export const useCancelOrder = () => {
  const cancelLoading = ref(false)
  const cancelEvent = async (item: patientConsultOrderListApiRowsItem) => {
    cancelLoading.value = true
    try {
      await patientOrderCancel(item.id)
      item.status = OrderType.ConsultCancel
      item.statusValue = '已取消'
    } finally {
      cancelLoading.value = false
    }
  }
  return {
    cancelLoading,
    cancelEvent
  }
}

// 删除
export const useDelOrder = (cb?: () => void) => {
  const delLoading = ref(false)
  const delEvent = async (id: string) => {
    delLoading.value = true
    try {
      await patientOrder(id)
      cb && cb()
      // emits('delItem', id)
    } finally {
      delLoading.value = false
    }
  }
  return { delEvent, delLoading }
}

// 处方预览
export const useLookEvent = () => {
  const lookEvent = async (id: string) => {
    // 调用接口获取处方图片
    const res = await patientConsultPrescription(id)
    console.log(res.data.url)
    showImagePreview([res.data.url])
  }
  return lookEvent
}
